package com.pet.shop.controller;

import com.pet.shop.model.Cart;
import com.pet.shop.model.User;
import com.pet.shop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Author Hxx
 * @Description //TODO 购物车 Controller
 * @Date 10:30 2020/4/7
 * @Param
 * @return
 **/

@RequestMapping("/Cart")
@Controller
public class CartController {
    @Autowired
    private CartService cartService;


    /**
     * 查看购物车
     *
     * @return
     */
    @RequestMapping("/queryCart")
    public String queryAll(Model model, HttpServletRequest request) {
//        获取当前登录用户信息
        User user = (User) request.getSession().getAttribute("User");
//        如果当前用户未登录，跳转到登录页面，否则跳转到购物车
        if (Objects.isNull(user)) {
            return "redirect:/login";
        }

        Assert.notNull(user.getId(), "当前登录者ID不能为空!");
        model.addAttribute("Cart", cartService.queryAll(user.getId()));
        return "shopcart";
    }

    /**
     * 添加购物车
     */
    @ResponseBody
    @RequestMapping("/addIntoCart")
    public String addIntoCart(Cart cart, HttpServletRequest request) {
        Assert.notNull(cart, "添加到购物车的商品不能为空");
        //订单可用
        User user = (User) request.getSession().getAttribute("User");
        if (Objects.isNull(user)) {
            return "未登录";
        }
        //登录用户ID
        cart.setBid(user.getId());
        //订单状态可用
        cart.setStatus(1);
        cartService.addIntoCart(cart);
        return "success";
    }
}
